package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.base.bean.BaseEnum;
import com.fz.us.oa.core.entity.com.*;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.*;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by dzw on 2018/3/19.
 * 主任信息 （表单和person都是一样的）
 */
@Controller
@RequestMapping("/com/director")
public class DirectorController extends BaseController {
    private static final long serialVersionUID = -2678322279792005572L;

    @Autowired
    private PersonService personService;
    @Autowired
    private DirectorService directorService;
    @Autowired
    private ResidentService residentService;
    @Autowired
    private StudyService studyService;
    @Autowired
    private WorkService workService;
    @Autowired
    private FamilyService familyService;

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model, String keyId, Integer isDirector, String draft, String index, String todo, String remind, String record){
        if(StringUtils.isNotEmpty(keyId)){
            Director director = directorService.get(keyId);
            model.addAttribute("person", director);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit = isEdit(keyId);
            model.addAttribute("stepNo", stepNo);
            model.addAttribute("isEdit", isEdit);
        }
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        model.addAttribute("isDirector", 1);

        return "/com/person_read";
    }

    /**
     * 赋值数据
     */
    public Director setData(User user, String keyId, String name, String gender, String birthday, String nationId, String origin, String birthPlace, String joinPartyDate,
                          String joinWorkDate, String health, String specialty, String workNatureId, String personNatureId, String highEduId, String allDayEduId, String allDaySchool,
                          String jobEduId, String jobSchool, String nowPost, String nowPostDate, String area, String streetId, String residentId, String photoIds, String reward,
                          String familyAddress, String phone, String zipCode, String studyJSON, String workJSON, String familyJSON, Integer shoulder, String shoulderDet, String zzmm,
                            String cardId){
        Director director = null;
        if(StringUtils.isNotEmpty(keyId)){
            director = directorService.get(keyId);
        }else{
            director = new Director();
            director.setCompany(user.getCompany());
            director.setCreater(user);
        }
        director.setZzmm(zzmm);
        director.setName(name);
        director.setGender(gender);
        director.setBirthday(DataUtil.StringToDate(birthday));
        director.setNation(dictItemService.get(nationId));
        director.setOrigin(origin);
        director.setBirthPlace(birthPlace);
        director.setJoinPartyDate(DataUtil.StringToDate(joinPartyDate));
        director.setJoinWorkDate(DataUtil.StringToDate(joinWorkDate));
        director.setHealth(health);
        director.setSpecialty(specialty);
        director.setWorkNature(dictItemService.get(workNatureId));
        director.setPersonNature(dictItemService.get(personNatureId));
        director.setHighEdu(dictItemService.get(highEduId));
        director.setAllDayEdu(dictItemService.get(allDayEduId));
        director.setAllDaySchool(allDaySchool);
        director.setJobEdu(dictItemService.get(jobEduId));
        director.setJobSchool(jobSchool);
        director.setNowPost(nowPost);
        director.setNowPostDate(DataUtil.StringToDate(nowPostDate));
        director.setArea(area);
        director.setStreet(dictItemService.get(streetId));
        director.setResident(residentService.get(residentId));
        director.setReward(reward);
        director.setFamilyAddress(familyAddress);
        director.setPhone(phone);
        director.setZipCode(zipCode);
        director.setShoulder(shoulder);
        director.setShoulderDet(shoulderDet);
        director.setCardId(cardId);

        //保存头像
        if(StringUtils.isNotEmpty(photoIds)){
            List<FileManage> fileManageList = new ArrayList<FileManage>();
            for(String s:photoIds.split(",")){
                fileManageList.add(fileManagerService.get(s.trim()));
            }
            if(fileManageList.size()>0){
                director.setPhoto(fileManageList.get(0));
            }
        }

        //保存学习经历
        if(StringUtils.isNotEmpty(studyJSON)){
            JSONArray sJSON = JSONArray.fromObject(studyJSON);
            List<Study> studyList = new ArrayList<Study>();
            for(int i=0;i<sJSON.size();i++){
                String startDate = sJSON.getJSONObject(i).getString("startDate");
                String endDate = sJSON.getJSONObject(i).getString("endDate");
                String school = sJSON.getJSONObject(i).getString("school");
                String academicDegree = sJSON.getJSONObject(i).getString("academicDegree");
                if(StringUtils.isNotEmpty(startDate) || StringUtils.isNotEmpty(endDate) || StringUtils.isNotEmpty(school) || StringUtils.isNotEmpty(academicDegree)){
                    Study study = new Study();
                    study.setCreater(user);
                    study.setCompany(user.getCompany());
                    study.setStartDate(DataUtil.StringToDate(startDate));
                    study.setEndDate(DataUtil.StringToDate(endDate));
                    study.setSchool(school);
                    study.setAcademicDegree(academicDegree);
                    studyService.save(study);
                    studyList.add(study);
                }
            }
            director.setStudyList(studyList);
        }

        //保存工作经历
        if(StringUtils.isNotEmpty(workJSON)){
            JSONArray wJSON = JSONArray.fromObject(workJSON);
            List<Work> workList = new ArrayList<Work>();
            for(int i=0;i<wJSON.size();i++){
                String workStartDate = wJSON.getJSONObject(i).getString("workStartDate");
                String workEndDate = wJSON.getJSONObject(i).getString("workEndDate");
                String workDept = wJSON.getJSONObject(i).getString("workDept");
                String workPost = wJSON.getJSONObject(i).getString("workPost");
                String proveUser = wJSON.getJSONObject(i).getString("proveUser");
                if(StringUtils.isNotEmpty(workStartDate) || StringUtils.isNotEmpty(workEndDate) || StringUtils.isNotEmpty(workDept) || StringUtils.isNotEmpty(workPost) || StringUtils.isNotEmpty(proveUser)){
                    Work work = new Work();
                    work.setCreater(user);
                    work.setCompany(user.getCompany());
                    work.setWorkStartDate(DataUtil.StringToDate(workStartDate));
                    work.setWorkEndDate(DataUtil.StringToDate(workEndDate));
                    work.setWorkDept(workDept);
                    work.setWorkPost(workPost);
                    work.setProveUser(proveUser);
                    workService.save(work);
                    workList.add(work);
                }
            }
            director.setWorkList(workList);
        }

        //保存家庭信息
        if(StringUtils.isNotEmpty(familyJSON)){
            JSONArray fJSON = JSONArray.fromObject(familyJSON);
            List<Family> familyList = new ArrayList<Family>();
            for(int i=0;i<fJSON.size();i++){
                String nickName = fJSON.getJSONObject(i).getString("nickName");
                String familyName = fJSON.getJSONObject(i).getString("familyName");
                String familyBirthday = fJSON.getJSONObject(i).getString("familyBirthday");
                String politicalStatus = fJSON.getJSONObject(i).getString("politicalStatus");
                String familyEdu = fJSON.getJSONObject(i).getString("familyEdu");
                String familyJob = fJSON.getJSONObject(i).getString("familyJob");
                if(StringUtils.isNotEmpty(nickName) || StringUtils.isNotEmpty(familyName) || StringUtils.isNotEmpty(familyBirthday) || StringUtils.isNotEmpty(politicalStatus) || StringUtils.isNotEmpty(familyEdu) || StringUtils.isNotEmpty(familyJob)){
                    Family family = new Family();
                    family.setCreater(user);
                    family.setCompany(user.getCompany());
                    family.setNickName(nickName);
                    family.setFamilyName(familyName);
                    family.setFamilyBirthday(DataUtil.StringToDate(familyBirthday));
                    family.setPoliticalStatus(politicalStatus);
                    family.setFamilyEdu(familyEdu);
                    family.setFamilyJob(familyJob);
                    familyService.save(family);
                    familyList.add(family);
                }
            }
            director.setFamilyList(familyList);
        }


        return director;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String keyId, String name, String gender, String birthday, String nationId, String origin, String birthPlace, String joinPartyDate,
                       String joinWorkDate, String health, String specialty, String workNatureId, String personNatureId, String highEduId, String allDayEduId, String allDaySchool,
                       String jobEduId, String jobSchool, String nowPost, String nowPostDate, String area, String streetId, String residentId, String photoIds, String reward,
                       String familyAddress, String phone, String zipCode, String studyJSON, String workJSON, String familyJSON, Integer shoulder, String shoulderDet, String zzmm,
                       String cardId){
        Map<String, Object> rMap = new HashMap<String, Object>();
        Director director = setData(user,keyId,name,gender,birthday,nationId,origin,birthPlace,joinPartyDate,joinWorkDate,health,
                specialty,workNatureId,personNatureId,highEduId,allDayEduId,allDaySchool,jobEduId,jobSchool,nowPost,nowPostDate,
                area,streetId,residentId,photoIds,reward,familyAddress,phone,zipCode,studyJSON,workJSON,familyJSON,shoulder,shoulderDet,zzmm,cardId);
        if(StringUtils.isNotEmpty(keyId)){
            directorService.update(director);
            rMap.put("message", "更新成功");
        }else{
            directorService.save(director, "com.fz.us.oa.core.entity.com.Director");
            rMap.put("message", "保存成功");
        }

        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, String keyId, String name, String gender, String birthday, String nationId, String origin, String birthPlace, String joinPartyDate,
                         String joinWorkDate, String health, String specialty, String workNatureId, String personNatureId, String highEduId, String allDayEduId, String allDaySchool,
                         String jobEduId, String jobSchool, String nowPost, String nowPostDate, String area, String streetId, String residentId, String photoIds, String reward,
                         String familyAddress, String phone, String zipCode, String studyJSON, String workJSON, String familyJSON, String curDutyId, String comment, Integer shoulder,
                         String shoulderDet, String zzmm, String cardId){
        Map<String, Object> rMap = new HashMap<String, Object>();
        Director director = setData(user, keyId, name, gender, birthday, nationId, origin, birthPlace, joinPartyDate, joinWorkDate, health,
                specialty, workNatureId, personNatureId, highEduId, allDayEduId, allDaySchool, jobEduId, jobSchool, nowPost, nowPostDate,
                area, streetId, residentId, photoIds, reward, familyAddress, phone, zipCode, studyJSON, workJSON, familyJSON, shoulder,
                shoulderDet, zzmm, cardId);
        if (StringUtils.isNotEmpty(keyId)) {
            directorService.approve(director, dutyService.get(curDutyId), comment);
        } else {
            directorService.commit(director, "com.fz.us.oa.core.entity.com.Director", dutyService.get(curDutyId));
        }
        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 审批
     */
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId, String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Director director = directorService.get(keyId);
        directorService.approve(director, dutyService.get(curDutyId), comment);
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 退回
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId, String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Director director = directorService.get(keyId);
            directorService.back(director, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 否决
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId, String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Director director = directorService.get(keyId);
            directorService.deny(director, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }



    // ===========统计明细功能======

    //获取一个人的年龄
    public int getAge(Director director){
        int userYear = Integer.parseInt(DataUtil.DateToString(director.getBirthday(), "yyyy"));
        int thisYear = Integer.parseInt(DataUtil.DateToString(new Date(), "yyyy"));
        return thisYear-userYear;
    }

    /**
     * 学历-全区 （也是统计明细的首页） （streetId不为空的话就是 学历-街道）
     */
    @RequestMapping(value = "eduAll", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String eduAll(@CurrentUser User user, Model model, String streetId){
        DecimalFormat df = new DecimalFormat("0.00%");
        List<DictItem> eduList = getDictItems(user, "edu");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        Map<String, Object> rMap;

        List<Rule> rules = new ArrayList<Rule>();
        if(StringUtils.isNotEmpty(streetId)){
            rules.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        int allCount = directorService.findPerson(rules).size();//所有人数
        BigDecimal allCountB = new BigDecimal(allCount);


        for(DictItem edu:eduList){
            rMap = new HashMap<String, Object>();
            int count = 0;
            if(StringUtils.isEmpty(streetId)){
                count = directorService.getCountEduAll(edu);
            }else{
                count = directorService.getCountEduAll(edu,dictItemService.get(streetId));
            }
            rMap.put("eduName", edu.getName());
            rMap.put("personCount", count);
            if(allCount!=0){
                rMap.put("bili", df.format(new BigDecimal(count).divide(allCountB,2,BigDecimal.ROUND_UP)));
            }else{
                rMap.put("bili", "0%");
            }
            list.add(rMap);
        }

        model.addAttribute("list", list);
        model.addAttribute("num", allCount);

        List<DictItem> streetList = getDictItems(user, "street");
        if(streetList.size()>0){
            model.addAttribute("firstStreetId", streetList.get(0).getId());
        }

        if(StringUtils.isEmpty(streetId)){
            return "/dirDet/edu_all";
        }else{
            model.addAttribute("streetList", streetList);
            model.addAttribute("selectStreetId", streetId);
            return "/dirDet/edu_street";
        }
    }


    /**
     * 性别年龄-全区  （如果streetId不为空，那就是年龄性别-街道）
     */
    @RequestMapping(value = "ageAll", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String ageAll(@CurrentUser User user, Model model, String streetId){
        DecimalFormat df = new DecimalFormat("0.00%");

        List<Rule> rules5 = new ArrayList<Rule>();
        rules5.add(RuleHelper.eq("gender", "男"));
        rules5.add(RuleHelper.eq("state", BaseEnum.StateEnum.Enable));
        if(StringUtils.isNotEmpty(streetId)){
            rules5.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        Long nan0 = directorService.findCountBySearch(rules5).getCount(); //合计男人数

        List<Rule> rules6 = new ArrayList<Rule>();
        rules6.add(RuleHelper.eq("gender", "女"));
        rules6.add(RuleHelper.eq("state", BaseEnum.StateEnum.Enable));
        if(StringUtils.isNotEmpty(streetId)){
            rules6.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        Long nv0 = directorService.findCountBySearch(rules6).getCount(); //合计女人数

        int age0 = 0;

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("state", BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(streetId)){
            params.put("street", dictItemService.get(streetId));
        }
        List<Director> directorList = directorService.getList(params); //当前总人数
        for(Director director:directorList){
            int thisAge = getAge(director);
            age0+=thisAge;
        }

        BigDecimal ageB0 = new BigDecimal(age0);
        BigDecimal countB0 = new BigDecimal(directorList.size()); //当前总人数
        model.addAttribute("nan0", nan0);
        model.addAttribute("nv0", nv0);

        model.addAttribute("avgAge0", directorList.size()==0 ? 0 : ageB0.divide(countB0, 2, BigDecimal.ROUND_UP));
        model.addAttribute("nan0Bili", directorList.size()==0 ? "0%" : df.format(new BigDecimal(nan0).divide(countB0,2,BigDecimal.ROUND_UP)));
        model.addAttribute("nv0Bili", directorList.size()==0 ? "0%" : df.format(new BigDecimal(nv0).divide(countB0,2,BigDecimal.ROUND_UP)));

        if(StringUtils.isEmpty(streetId)){
            return "/dirDet/age_all";
        }else{
            List<DictItem> streetList = getDictItems(user, "street");
            model.addAttribute("streetList", streetList);
            model.addAttribute("selectStreetId", streetId);
            return "/dirDet/age_street";
        }

    }


    /**
     * 党员性质-全区 （如果streetId不为空，那就是 人员性质-街道）
     */
    @RequestMapping(value = "personNatureAll", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String personNatureAll(@CurrentUser User user, Model model, String streetId){
        DecimalFormat df = new DecimalFormat("0.00%");

        DictItem street = null;
        if(StringUtils.isNotEmpty(streetId)){
            street = dictItemService.get(streetId);
        }

        int allCount = 0;
        if(street==null){
            allCount = directorService.getAllCount();
        }else{
            allCount = directorService.getCountByStreet(street);
        }
        model.addAttribute("allCount", allCount);

        BigDecimal allCountB = new BigDecimal(allCount);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> rMap;

        List<Rule> rules = new ArrayList<Rule>();
        if(StringUtils.isNotEmpty(streetId)){
            rules.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        rules.add(RuleHelper.isNotNull("joinPartyDate"));
        int dangyuanCount = directorService.findPerson(rules).size(); //党员数量
        int feidangyuanCount = allCount - dangyuanCount; //非党员数量

        rMap = new HashMap<String, Object>();
        rMap.put("natureName", "党员数量");
        rMap.put("natureCount", String.valueOf(dangyuanCount));
        rMap.put("bili", allCount==0 ? "0%" : df.format(new BigDecimal(dangyuanCount).divide(allCountB,2,BigDecimal.ROUND_UP)));
        list.add(rMap);

        rMap = new HashMap<String, Object>();
        rMap.put("natureName", "非党员数量");
        rMap.put("natureCount", String.valueOf(feidangyuanCount));
        rMap.put("bili", allCount==0 ? "0%" : df.format(new BigDecimal(feidangyuanCount).divide(allCountB,2,BigDecimal.ROUND_UP)));
        list.add(rMap);

        model.addAttribute("list", list);

        if(StringUtils.isEmpty(streetId)){
            return "/dirDet/person_nature_all";
        }else{
            List<DictItem> streetList = getDictItems(user, "street");
            model.addAttribute("streetList", streetList);
            model.addAttribute("selectStreetId", streetId);
            return "/dirDet/person_nature_street";
        }
    }


    //统计汇总 打开dialog


    /**
     * 根据街道打开人员列表 性别分类
     */
    @RequestMapping(value = "openPerson", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String openPerson(@CurrentUser User user, Model model, String streetId){
        if(StringUtils.isNotEmpty(streetId)){

            List<Rule> rules = new ArrayList<Rule>();
            rules.add(RuleHelper.eq("street", dictItemService.get(streetId)));
            List<Director> personList = directorService.findPerson(rules);

            List<Map<String, Object>> personList0 = new ArrayList<Map<String, Object>>();
            List<Map<String, Object>> personList1 = new ArrayList<Map<String, Object>>();
            Map<String, Object> rMap;
            for(Director director:personList){
                rMap = new HashMap<String, Object>();
                rMap.put("id", director.getId());
                rMap.put("name", director.getName());
                rMap.put("age", getAge(director));
                if("女".equals(director.getGender())){
                    personList0.add(rMap);
                }else{
                    personList1.add(rMap);
                }
            }

            model.addAttribute("personList0", personList0);
            model.addAttribute("personList1", personList1);
        }
        return "/com/person_list_dialog";
    }

    /**
     * 根据街道打开人员列表 大专分类
     */
    @RequestMapping(value = "openDaZhuanPerson", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String openDaZhuanPerson(@CurrentUser User user, Model model, String streetId){
        List<Rule> rules = new ArrayList<Rule>();
        rules.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        List<Director> directorList = directorService.findPerson(rules);

        List<Map<String, Object>> personList0 = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> personList1 = new ArrayList<Map<String, Object>>();
        Map<String, Object> rMap;
        for(Director director:directorList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", director.getId());
            rMap.put("name", director.getName());
            rMap.put("edu", director.getHighEdu()!=null?director.getHighEdu().getName():"");
            rMap.put("age", director.getGender());
            String thisEdu = director.getHighEdu()!=null ? director.getHighEdu().getValue() : "";
            if("edu4".equals(thisEdu) || "edu5".equals(thisEdu) || "edu6".equals(thisEdu)){

                if(director.getAllDayEdu()!=null && thisEdu.equals(director.getAllDayEdu().getValue())){
                    rMap.put("nature", "全日制教育");
                }else if(director.getJobEdu()!=null && thisEdu.equals(director.getJobEdu().getValue())){
                    rMap.put("nature", "在职教育");
                }else{
                    rMap.put("nature", "");
                }

                personList0.add(rMap);
            }else{
                personList1.add(rMap);
            }
        }

        model.addAttribute("personList0", personList0);
        model.addAttribute("personList1", personList1);

        return "/com/person_daZhuan_dialog";
    }


}
